package com.ruoyi.web.controller.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.properties.CasProperties;
import com.ruoyi.framework.web.service.CasLoginService;

/**
 * CAS单点登录控制器
 * 
 * @author ruoyi
 */
@Controller
@ConditionalOnProperty(prefix = "cas", name = "enabled", havingValue = "true")
public class SysCasController
{
    @Autowired
    private CasLoginService casLoginService;
    
    @Autowired
    private CasProperties casProperties;
    
    /**
     * CAS登录成功后跳转的地址，生成JWT Token并重定向到前端页面
     */
    @GetMapping("/cas/login")
    public String casLoginRedirect(HttpServletRequest request, HttpServletResponse response)
    {
        // 处理CAS登录，获取令牌
        String token = casLoginService.handleCasLogin(request);
        
        if (StringUtils.isNotEmpty(token))
        {
            // 重定向到前端首页，并带上token参数
            return "redirect:" + casProperties.getClientHostUrl() + "/index?token=" + token;
        }
        else
        {
            // 登录失败则重定向到登录页面
            return "redirect:" + casProperties.getClientHostUrl() + "/login";
        }
    }
    
    /**
     * APP登录API接口，通过CAS认证后返回JWT Token
     */
    @GetMapping("/api/cas/login")
    @ResponseBody
    public AjaxResult apiCasLogin(HttpServletRequest request)
    {
        // 处理CAS登录，获取令牌
        String token = casLoginService.handleCasLogin(request);
        
        if (StringUtils.isNotEmpty(token))
        {
            AjaxResult ajax = AjaxResult.success("CAS单点登录成功");
            ajax.put(Constants.TOKEN, token);
            return ajax;
        }
        else
        {
            return AjaxResult.error("CAS单点登录失败");
        }
    }
    
    /**
     * CAS登出
     */
    @GetMapping("/cas/logout")
    public String casLogout()
    {
        return "redirect:" + casProperties.getLogoutUrl();
    }
} 